'use strict'

const { CryptUtil } = require('../Util')
const { ERR } = require('../../../constants')
const { User } = require('../Models')

class UserAuth {
  async handle({ request }, next) {
    const payload = CryptUtil.jwtDecode(request.plainCookie('token') || request.header('Authorization') || request.input('token'))

    
    if (!payload) {
      throw ERR.AUTH_FAILED
    } else {
      if (!payload.userID) {
        throw ERR.AUTH_FAILED
      }
      let user = await User.find(payload.userID)
      if (!user) {
        throw ERR.USER_NOT_EXISTS
      }
      request.userID = payload.userID
      request.user = user
    }
    await next()
  }
}

module.exports = UserAuth
